import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:connectivity_plus/connectivity_plus.dart';

class HttpClient {
  static const String baseUrl = "https://jsonplaceholder.typicode.com";

  static Map<String, String> get _defaultHeaders => {
    "Content-Type": "application/json",
    "Accept": "application/json",
  };

  // GET 请求
  static Future<http.Response> get(String path) async {
    return _executeRequest(() async {
      return await http.get(
        Uri.parse("$baseUrl$path"),
        headers: _defaultHeaders,
      );
    });
  }

  // POST 请求 - 修复后的实现
  static Future<http.Response> post(
      String path, {
        Map<String, dynamic>? body,
        Map<String, String>? headers,
      }) async {
    final mergedHeaders = {
      ..._defaultHeaders,
      ...?headers,
    };

    return _executeRequest(() async {
      return await http.post(
        Uri.parse("$baseUrl$path"),
        headers: mergedHeaders,
        body: body != null ? jsonEncode(body) : null,
      );
    });
  }

  // 统一执行请求并处理 - 修复参数传递
  static Future<http.Response> _executeRequest(
      Future<http.Response> Function() requestFunction, // 修复参数类型
      ) async {
    try {
      // 1. 检查网络连接
      final connectivityResult = await Connectivity().checkConnectivity();
      if (connectivityResult == ConnectivityResult.none) {
        throw "No internet connection";
      }

      // 2. 执行请求
      final response = await requestFunction().timeout(const Duration(seconds: 10));

      // 3. 处理响应
      return _handleResponse(response);
    } on http.ClientException catch (e) {
      throw "ClientException: ${e.message}";
    } catch (e) {
      throw "Network error: ${e.toString()}";
    }
  }

  // 处理响应
  static http.Response _handleResponse(http.Response response) {
    final status = response.statusCode;

    if (status >= 200 && status < 300) {
      return response;
    } else {
      final errorDetails = {
        'status': status,
        'url': response.request?.url.toString(),
        'body': response.body.length > 200
            ? response.body.substring(0, 200) + '...'
            : response.body
      };
      throw "HTTP Error ${status}: ${jsonEncode(errorDetails)}";
    }
  }
}